<template>
  <div v-loading="loading">
    <el-breadcrumb>
      <el-breadcrumb-item
        :to="{ path: '/government/subsidy' }"
      >运营补贴管理</el-breadcrumb-item>
      <el-breadcrumb-item>申请补贴</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="cad-box" style="margin: 20px 0; padding-top: 0px">
      <div style="width: 100%; margin-top: 40px">
        <div class="obj_title">基本信息</div>
        <div class="obj_box">
          <div style="width: 100%">
            <el-form
              ref="ruleForm"
              :model="ruleForm"
              :rules="rules"
              label-width="100px"
              class="demo-ruleForm"
              style="display: flex; flex-wrap: wrap"
            >
              <el-form-item
                label="机构名称"
                prop="institutionName"
                style="width: 80%"
              >
                <el-input
                  v-model="ruleForm.institutionName"
                  placeholder="请输入机构名称"
                  :disabled="disabled"
                />
              </el-form-item>
              <el-form-item
                label="机构地址"
                prop="institutionAddress"
                style="width: 80%"
              >
                <el-input
                  v-model="ruleForm.institutionAddress"
                  placeholder="请输入机构地址"
                  :disabled="disabled"
                />
              </el-form-item>
              <el-form-item
                label="负责人"
                prop="responsiblePerson"
                style="width: 40%"
              >
                <el-input
                  v-model="ruleForm.responsiblePerson"
                  placeholder="请输入负责人"
                  :disabled="disabled"
                />
              </el-form-item>
              <el-form-item
                label="联系方式"
                prop="contactInfo"
                style="width: 40%"
              >
                <el-input
                  v-model="ruleForm.contactInfo"
                  placeholder="请输入联系方式"
                  :disabled="disabled"
                />
              </el-form-item>

              <el-form-item
                label="机构类型"
                prop="institutionType"
                style="width: 40%"
              >
                <el-select
                  v-model="ruleForm.institutionType"
                  style="width: 100%"
                  placeholder="请选择机构类型"
                  :disabled="disabled"
                >
                  <el-option label="请选择" :value="0" />
                  <el-option label="托育中心" :value="1" />
                  <el-option label="用人单位托育点" :value="2" />
                  <el-option label="幼儿园" :value="3" />
                  <el-option label="托育综合服务中心" :value="4" />
                </el-select>
              </el-form-item>
              <el-form-item
                label="机构性质"
                prop="institutionNature"
                style="width: 40%"
              >
                <el-select
                  v-model="ruleForm.institutionNature"
                  style="width: 100%"
                  placeholder="请选择机构性质"
                  :disabled="disabled"
                >
                  <el-option label="请选择" :value="0" />
                  <el-option label="公办" :value="1" />
                  <el-option label="民办" :value="2" />
                  <el-option label="公办民营" :value="3" />
                </el-select>
              </el-form-item>
              <el-form-item
                label="核定托位数"
                prop="approvedCapacity"
                style="width: 40%"
              >
                <el-input
                  v-model="ruleForm.approvedCapacity"
                  placeholder="请输入核定托位数（个）"
                  :disabled="disabled"
                  type="number"
                  min="0"
                />
              </el-form-item>
              <el-form-item
                label="注册机关"
                prop="registrationAuthority"
                style="width: 40%"
              >
                <el-input
                  v-model="ruleForm.registrationAuthority"
                  placeholder="请输入登记注册机关"
                  :disabled="disabled"
                />
              </el-form-item>

              <el-form-item
                label="备案机关"
                prop="filingAuthority"
                style="width: 40%"
              >
                <el-input
                  v-model="ruleForm.filingAuthority"
                  placeholder="请输入备案机关"
                  :disabled="disabled"
                />
              </el-form-item>
              <el-form-item label="开户行" prop="bankName" style="width: 40%">
                <el-input
                  v-model="ruleForm.bankName"
                  placeholder="请输入开户行"
                  :disabled="disabled"
                />
              </el-form-item>

              <el-form-item
                label="银行卡号"
                prop="bankCardNumber"
                style="width: 40%"
              >
                <el-input
                  v-model="ruleForm.bankCardNumber"
                  placeholder="请输入银行卡号"
                  :disabled="disabled"
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>

    <div class="cad-box" style="margin: 20px 0">
      <div class="obj_title">其他证明文件</div>
      <div
        v-for="(item, index) in fielForList"
        :key="index"
        class="obj_bt_box"
        style="display: flex; margin-top: 30px"
      >
        <div class="box_label" style="width: 150px">
          <span style="color: red; margin-right: 4px">*</span>
          <span>{{ `${item.name}` }}：</span>
          <div v-if="dataObj[item.status] === 0" style="color: red">
            {{ `（不通过）` }}
          </div>
          <div v-if="dataObj[item.status] === 1" style="color: green">
            {{ `（通过）` }}
          </div>
        </div>
        <div class="box_value">
          <el-upload
            style="position: relative; min-height: 148px"
            action="/api/system/upload1"
            list-type="picture-card"
            :auto-upload="true"
            :file-list="fileSumList[item.filelistShowName]"
            :on-success="
              (response, file, fileList) =>
                handleFileSuccess(response, file, fileList, item)
            "
            :disabled="disabled"
            :before-upload="handleBefore"
          >
            <i slot="default" class="el-icon-plus" />
            <div slot="file" slot-scope="{ file }">
              <img
                style="height: 148px"
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              >
              <div
                class="text"
                style="display: block; max-width: 148px; word-break: break-all"
              >
                {{ file.name ? file.name : "" }}
              </div>
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in" />
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                  <i class="el-icon-download" />
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file, item)"
                >
                  <i class="el-icon-delete" />
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </div>
      </div>
    </div>
    <div
      v-if="!disabled"
      class="cad-box flex-card"
      style="margin: 20px 0; justify-content: space-evenly"
    >
      <el-button type="warning" @click="handleSubmit">确 认</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  govCapitalSubsidyProjectApply,
  govCapitalSubsidyProjectDetails
} from './api/index.js'
import positionData from '@/assets/ssq.js'
import fileImage from '@/assets/file_image.png'
export default {
  data () {
    return {
      positionData,
      fileListOtherShow: [],
      fileListOther: [],
      ruleForm: {
        institutionName: '', // 机构名称
        institutionAddress: '', // 机构地址
        responsiblePerson: '', // 负责人
        contactInfo: '', // 联系方式
        institutionType: '', // 机构类型
        institutionNature: '', // 机构性质
        approvedCapacity: '', // 核定托位数
        registrationAuthority: '', // 登记注册机关
        filingAuthority: '', // 备案机关
        bankName: '', // 开户行
        bankCardNumber: '' // 银行卡号
      },

      rules: {
        institutionName: [
          { required: true, message: '请输入机构名称', trigger: 'blur' }
        ],
        institutionAddress: [
          { required: true, message: '请输入机构地址', trigger: 'blur' }
        ],
        responsiblePerson: [
          { required: true, message: '请输入负责人', trigger: 'blur' }
        ],
        contactInfo: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '手机号码格式不正确',
            trigger: 'blur'
          }
        ],
        institutionType: [
          { required: true, message: '请输入机构类型', trigger: 'change' }
        ],
        institutionNature: [
          {
            required: true,
            message: '请选择机构性质',
            trigger: 'change'
          }
        ],
        approvedCapacity: [
          { required: true, message: '请输入核定托位数', trigger: 'blur' }
        ],
        registrationAuthority: [
          { required: true, message: '请输入登记注册机关', trigger: 'blur' }
        ],
        filingAuthority: [
          { required: true, message: '请输入备案机关', trigger: 'blur' }
        ],
        bankName: [
          { required: true, message: '请输入开户行', trigger: 'blur' }
        ],
        bankCardNumber: [
          { required: true, message: '请输入银行卡号', trigger: 'blur' }
        ]
      },
      loading: false,
      idS: '',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      fileImage,
      fileSumList: {
        fileList: [],
        fileListShow: [],
        fileList1: [],
        fileListShow1: [],
        fileList2: [],
        fileListShow2: [],
        fileList3: [],
        fileListShow3: [],
        fileList4: [],
        fileListShow4: [],
        fileList5: [],
        fileListShow5: [],
        fileList6: [],
        fileListShow6: [],
        fileList7: [],
        fileListShow7: []
      },
      fromdata: {
        name: '',
        time: '',
        html: ''
      },
      fielForList: [
        {
          name: '托位使用证明',
          filelistName: 'fileList',
          filelistShowName: 'fileListShow',
          status: 'businessLicenseStatus'
        },
        {
          name: '营业执照',
          filelistName: 'fileList1',
          filelistShowName: 'fileListShow1',
          status: 'healthEvalStatus'
        },
        {
          name: '服务质量评估等级',
          filelistName: 'fileList2',
          filelistShowName: 'fileListShow2',
          status: 'foodLicenseStatus'
        },
        {
          name: '卫生评价报告',
          filelistName: 'fileList3',
          filelistShowName: 'fileListShow3',
          status: 'areaUrlStatus'
        },
        {
          name: '补贴申请',
          filelistName: 'fileList4',
          filelistShowName: 'fileListShow4',
          status: 'locationProofStatus'
        },
        {
          name: '入托情况明细表',
          filelistName: 'fileList5',
          filelistShowName: 'fileListShow5',
          status: 'fireSafetyStatus'
        }
      ],
      caseShow: false,
      dataObj: {},
      listid: ''
    }
  },
  computed: {
    ...mapGetters(['curArea', 'user'])
  },
  async created () {
    const { type, id, listid } = this.$route.query
    this.idS = id
    this.listid = listid
    console.log(type)
    this.handleGovCapitalSubsidyProjectDetails()
  },

  mounted () {},
  methods: {
    async handleGovCapitalSubsidyProjectDetails () {
      const res = await govCapitalSubsidyProjectDetails({
        id: this.listid,
        areaId: this.curArea.id
      })
      console.log(res)
      this.ruleForm.approvedCapacity =
        res.govApplyForInstitution.approvedCapacity
      this.ruleForm.bankCardNumber = res.govApplyForInstitution.bankCardNumber
      this.ruleForm.bankName = res.govApplyForInstitution.bankName
      this.ruleForm.contactInfo = res.govApplyForInstitution.contactInfo
      this.ruleForm.filingAuthority =
        res.govApplyForInstitution.filingAuthority
      this.ruleForm.institutionAddress =
        res.govApplyForInstitution.institutionAddress
      this.ruleForm.institutionName =
        res.govApplyForInstitution.institutionName
      this.ruleForm.institutionNature = Number(
        res.govApplyForInstitution.institutionNature
      )
      this.ruleForm.institutionType = Number(
        res.govApplyForInstitution.institutionType
      )
      this.ruleForm.registrationAuthority =
        res.govApplyForInstitution.registrationAuthority
      this.ruleForm.responsiblePerson =
        res.govApplyForInstitution.responsiblePerson

      const businessLicense = JSON.parse(
        res.govApplyForInstitution.businessLicense
      )
      businessLicense.forEach((item, index) => {
        this.fileSumList.fileList1.push({
          url: item.url,
          name: item.name,
          uid: index + 1
        })
        this.fileSumList.fileListShow1.push(
          this.handleFileImage(item, index + 1)
        )
      })
      const capacityUsageProof = res.govApplyForInstitution.capacityUsageProof
      capacityUsageProof.forEach((item, index) => {
        this.fileSumList.fileList.push({
          url: item.url,
          name: item.name,
          uid: index + 1
        })
        this.fileSumList.fileListShow.push(
          this.handleFileImage(item, index + 1)
        )
      })
      const enrollmentDetails = res.govApplyForInstitution.enrollmentDetails
      enrollmentDetails.forEach((item, index) => {
        this.fileSumList.fileList5.push({
          url: item.url,
          name: item.name,
          uid: index + 1
        })
        this.fileSumList.fileListShow5.push(
          this.handleFileImage(item, index + 1)
        )
      })
      const healthEvaluationReport = healthEvaluationReport.forEach(
        (item, index) => {
          this.fileSumList.fileList3.push({
            url: item.url,
            name: item.name,
            uid: index + 1
          })
          this.fileSumList.fileListShow3.push(
            this.handleFileImage(item, index + 1)
          )
        }
      )
      const serviceQualityRating =
        res.govApplyForInstitution.serviceQualityRating
      serviceQualityRating.forEach((item, index) => {
        this.fileSumList.fileList2.push({
          url: item.url,
          name: item.name,
          uid: index + 1
        })
        this.fileSumList.fileListShow2.push(
          this.handleFileImage(item, index + 1)
        )
      })
      const subsidyApplication = res.govApplyForInstitution.subsidyApplication
      subsidyApplication.forEach((item, index) => {
        this.fileSumList.fileList4.push({
          url: item.url,
          name: item.name,
          uid: index + 1
        })
        this.fileSumList.fileListShow4.push(
          this.handleFileImage(item, index + 1)
        )
      })
    },
    handleFileImage (fileUrl, uid) {
      const fileExtension = fileUrl.url.split('.').pop()
      if (['jpg', 'jpeg', 'png', 'gif', 'svg'].includes(fileExtension)) {
        return {
          uid: uid,
          name: fileUrl.name,
          url: fileUrl.url,
          uploadFile: fileUrl.url
        }
      } else {
        return {
          uid: uid,
          name: fileUrl.name,
          url: fileImage,
          uploadFile: fileUrl.url
        }
      }
    },
    handleFileOtherSuccess (response, file, fileList, item) {
      this.fileListOther.push({
        uid: file.uid,
        name: response.data.name,
        url: response.data.url,
        uploadFile: response.data.url
      })
      let fileExtension = response.data.url.split('.').pop() // 获取文件后缀
      fileExtension = fileExtension.toLowerCase() // 将后缀转换为小写，以便比较
      if (['jpg', 'jpeg', 'png', 'gif', 'svg'].includes(fileExtension)) {
        this.fileListOtherShow.push({
          uid: file.uid,
          name: response.data.name,
          url: response.data.url,
          uploadFile: response.data.url
        })
      } else {
        this.fileListOtherShow.push({
          uid: file.uid,
          name: response.data.name,
          url: fileImage,
          uploadFile: response.data.url
        })
      }
    },
    handleRemove (file, item) {
      this.fileSumList[item.filelistName] = this.fileSumList[
        item.filelistName
      ].filter((eitem) => eitem.uid !== file.uid)
      console.log(
        this.fileSumList[item.filelistShowName],
        file,
        'handleRemove'
      )
      this.fileSumList[item.filelistShowName] = this.fileSumList[
        item.filelistShowName
      ].filter((eitem) => eitem.uid !== file.uid)
    },
    handleOhterRemove (file) {
      this.fileListOther = this.fileListOther.filter(
        (eitem) => eitem.uid !== file.uid
      )
      console.log(this.fileListOther, 'handleOhterRemove')
      this.fileListOtherShow = this.fileListOtherShow.filter(
        (eitem) => eitem.uid !== file.uid
      )
    },
    handleSubmit () {
      Promise.all([this.$refs['ruleForm'].validate()])
        .then(async () => {
          // 如果所有表单都验证通过
          console.log('所有表单验证通过')
          console.log('提交成功')
          const fileObj = {}
          this.fielForList.forEach((item) => {
            if (item.name === '托位使用证明') {
              fileObj.capacityUsageProof = JSON.stringify(
                this.fileSumList[item.filelistName]
              )
            }
            if (item.name === '营业执照') {
              fileObj.businessLicense = JSON.stringify(
                this.fileSumList[item.filelistName]
              )
            }
            if (item.name === '服务质量评估等级') {
              fileObj.serviceQualityRating = JSON.stringify(
                this.fileSumList[item.filelistName]
              )
            }
            if (item.name === '卫生评价报告') {
              fileObj.healthEvaluationReport = JSON.stringify(
                this.fileSumList[item.filelistName]
              )
            }
            if (item.name === '补贴申请') {
              fileObj.subsidyApplication = JSON.stringify(
                this.fileSumList[item.filelistName]
              )
            }
            if (item.name === '入托情况明细表') {
              fileObj.enrollmentDetails = JSON.stringify(
                this.fileSumList[item.filelistName]
              )
            }
          })
          if (fileObj.capacityUsageProof === '') {
            this.$message.warning('请上传托位使用证明')
            return false
          }
          if (fileObj.businessLicense === '') {
            this.$message.warning('请上传营业执照')
            return false
          }
          if (fileObj.serviceQualityRating === '') {
            this.$message.warning('请上传服务质量评估等级')
            return false
          }
          if (fileObj.healthEvaluationReport === '') {
            this.$message.warning('请上传卫生评价报告')
            return false
          }
          if (fileObj.subsidyApplication === '') {
            this.$message.warning('请上传补贴申请')
            return false
          }
          if (fileObj.enrollmentDetails === '') {
            this.$message.warning('请上传入托情况明细表')
            return false
          }
          await govCapitalSubsidyProjectApply({
            govApplyForInstitution: {
              ...this.ruleForm,
              ...fileObj,
              areaId: this.curArea.areaId,
              userId: this.user.id
              // capitalSubsidyProjectId: this.idS,
            },
            id: this.listid
          })
          this.$message.success('新增成功')
          this.$router.push('/government/subsidy')
        })
        .catch((error) => {
          // 如果有任何一个表单验证失败
          console.error('表单验证失败:', error)
        })
    },

    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload (file) {
      window.location.href = file.url
    },
    handleBefore (file) {
      console.log(file, 'handleBefore')
    },
    handleFileSuccess (response, file, fileList, item) {
      console.log(file, 'handleFileSuccess')
      this.fileSumList[item.filelistName].push({
        uid: file.uid,
        name: response.data.originalName,
        url: response.data.url
      })
      let fileExtension = response.data.url.split('.').pop() // 获取文件后缀
      fileExtension = fileExtension.toLowerCase() // 将后缀转换为小写，以便比较
      if (['jpg', 'jpeg', 'png', 'gif', 'svg'].includes(fileExtension)) {
        this.fileSumList[item.filelistShowName].push({
          uid: file.uid,
          name: response.data.originalName,
          url: response.data.url
        })
      } else {
        this.fileSumList[item.filelistShowName].push({
          uid: file.uid,
          name: response.data.originalName,
          url: fileImage
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-upload-list--picture-card .el-upload-list__item-thumbnail {
  border: 1px solid #c0ccda;
  border-radius: 10px;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item {
  border: none !important;
  height: auto !important;
}
::v-deep .el-upload--picture-card {
  position: absolute;
  right: -148px;
  top: 0;
}
::v-deep .el-upload-list--picture-card {
  display: flex !important;
}
::v-deep .el-upload-list__item {
  overflow: inherit;
}
::v-deep .el-form-item {
  margin-bottom: 50px !important;
}
.left-user {
  display: flex;
  justify-content: space-between;
  .left-user-info {
    margin-left: 10px;
    line-height: 30px;

    .name-item {
      font-weight: bold;
    }

    .message-item {
      font-size: 13px;
      color: #808080;
    }
  }
}
.obj_title {
  font-size: 18px;
  font-weight: bold;
}
.obj_box {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin-top: 20px;
  .obj_bt_box {
    width: 100%;
    display: flex;
    align-items: center;
    // .box_label {
    // }
    .box_value {
      margin: 30px 0px;
    }
  }
  .obj_item {
    width: 30%;
    padding: 20px 0px;
  }
}
.title-card {
  font-weight: bold;
  margin-bottom: 20px;
}

.flex-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content-box {
  display: flex;

  .left-message {
    width: 65%;
    padding-right: 150px;

    .demo-ruleForm {
      ::v-deep .el-form-item {
        margin-bottom: 22px;
      }

      .box-border {
        margin-bottom: 30px;
        border-top: 1px solid #ebebee;
      }
    }

    ::v-deep .el-form-item {
      margin-bottom: 55px;
    }
  }
  .right-record {
    flex: 1;
    padding-left: 30px;
    margin-left: 30px;

    ::v-deep .el-card {
      background-color: #f6f8fa;
      border: 1px solid #f6f8fa;
    }
    ::v-deep .is-always-shadow {
      box-shadow: none;
    }

    ::v-deep .el-timeline-item__timestamp {
      color: black;
      font-size: 15px;
    }

    .text-content {
      margin-top: 20px;
      color: #808080;
    }
  }
}
</style>
